﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using WebUI.Controls;

namespace WebUI
{
    public partial class CustomerOrders : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            gridOrder.OnNeedDataSource = gridOrder_OnNeedDataSource;
            gridSelectedItems.OnNeedDataSource = gridSelectedItems_OnNeedDataSource;
            gridOrder.OnClientClick = "loadByOrderID();";
            if (!IsPostBack)
            {
                OrderStatus status = new OrderStatus();
                status.LoadAll();
                Utilities.LoadDropDownList(ddlStatus, status.DefaultView, OrderStatus.ColumnNames.StatusName, OrderStatus.ColumnNames.ID, "--All--");
                ddlStatus.SelectedValue = OrderStatus.Pending.ToString();
                LoadByStatus();
            }

            ScriptManager.RegisterClientScriptInclude(this, typeof(Page), Guid.NewGuid().ToString(), "Script/prototype.js");
            ScriptManager.RegisterClientScriptInclude(this, typeof(Page), Guid.NewGuid().ToString(), "Script/scriptaculous.js?load=effects");
            ScriptManager.RegisterClientScriptInclude(this, typeof(Page), Guid.NewGuid().ToString(), "Script/lightbox.js");
        }

        public string GetOrderDetailEditPageLink()
        {
            return "EditPages/EditCustomerOrderDetails.aspx?";
        }

        protected void ddlStatus_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            LoadByStatus();
        }

        protected void btnPrintOrder_OnClick(object sender, EventArgs e)
        {
            CustomerOrderViewerCtrl printedList = (CustomerOrderViewerCtrl)LoadControl(@"~/Controls/POSControls/CustomerOrderViewerCtrl.ascx");
            printedList.LoadCustomerOrderByID(int.Parse(gridOrder.SelectedValue));
            Session[PrintKey] = printedList;
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);
        }

        protected void btnRemoveOrderItem_OnClick(object sender, EventArgs e)
        {
            gridSelectedItems.DeleteCheckedItems();
            gridSelectedItems.Refresh();
        }

        public string PrintKey
        {
            get
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string GetPrintPage()
        {
            return "EditPages/PrintHandler.aspx?key=" + PrintKey;
        }

        private void LoadByStatus()
        {
            if (ddlStatus.SelectedValue != "")
                SearchFilter = View_CustomerOrders.ColumnNames.StatusID + "=" + ddlStatus.SelectedValue + " and " + View_CustomerOrders.ColumnNames.BranchID + "=" + Branches.CurrentBranchID.ToString();
            else
                SearchFilter = View_CustomerOrders.ColumnNames.StatusID + "!=" + OrderStatus.Temporary.ToString() + " and " + View_CustomerOrders.ColumnNames.BranchID + "=" + Branches.CurrentBranchID.ToString();

            gridOrder.Refresh();
            updateGridOrder.Update();

            divDetails.Style["display"] = "none";
            updateItems.Update();
        }

        protected void btnReload_OnClick(object sender, EventArgs e)
        {
            SearchFilter = "";
            gridOrder.Refresh();
            updateGridOrder.Update();

            divDetails.Style["display"] = "none";
            updateItems.Update();
        }

        public string SearchFilter
        {
            get { return ViewState["SearchFilter"] == null ? "" : ViewState["SearchFilter"].ToString(); }
            set { ViewState["SearchFilter"] = value; }
        }

        protected void gridOrder_OnNeedDataSource(Object sender, EventArgs e)
        {
            View_CustomerOrders prods = new View_CustomerOrders();
            string cols = "*";
            string sort = gridOrder.SortExpression + " " + gridOrder.SortDirection;
            int totalRow = prods.Search(SearchFilter, cols, sort.Trim(), gridOrder.CurrentPageIndex * gridOrder.PageSize, gridOrder.PageSize);
            gridOrder.VirtualItemCount = totalRow;
            gridOrder.DataSource = prods.DefaultView;
        }

        protected void btnRemoveOrder_OnClick(object sender, EventArgs e)
        {
            gridOrder.DeleteCheckedItems();
            gridOrder.Refresh();
            divDetails.Style["display"] = "none";
        }

        protected void gridSelectedItems_OnNeedDataSource(Object sender, EventArgs e)
        {
            View_OrderItems prods = new View_OrderItems();
            string filter = View_OrderItems.ColumnNames.OrderID + "=" + hidOrderID.Value + " and " + View_OrderItems.ColumnNames.Deleted + " = 0" ;
            string cols = "*";
            int totalRow = prods.Search(filter, cols, "", 0, 9999);
            gridSelectedItems.DataSource = prods.DefaultView;

            ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), "initLightbox();", true); 
        }

        public void btnLoadByOrderID_OnClick(object sender, EventArgs e)
        {
            try
            {
                if (hidOrderID.Value == "")
                    return;
                hidOrderID.Value = hidOrderID.Value.Replace(",", "").Replace(";", "");
                gridSelectedItems.ReadOnly = true;
                gridSelectedItems.SelectedValue = "";
                gridSelectedItems.Refresh();

                divDetails.Style["display"] = "block";
                updateItems.Update();
            }
            catch (Exception ex)
            {
                ErrorLog.WriteToFile("MyOrder.aspx.cs", "btnLoadByOrderID_OnClick", ex.StackTrace);
            }
        }

        protected void btnEditItem_OnClick(object sender, EventArgs e)
        {
            gridOrder.Refresh();
            gridSelectedItems.Refresh();
            
            updateGridOrder.Update();
        }

        protected void btnPending_OnClick(object sender, EventArgs e)
        {
            if (hidOrderID.Value != "")
            {
                int orderID = int.Parse(hidOrderID.Value);
                UpdateStatus(orderID, OrderStatus.Pending);
            }
        }

        private void UpdateStatus(int id, int status)
        {
            POSSystem.BLL.CustomerOrders order = new POSSystem.BLL.CustomerOrders();
            order.LoadByPrimaryKey(id);

            if (order.StatusID == OrderStatus.InvoiceCreated )
            {
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), string.Format("alert('The invoice for this order has been created!');"), true);
                gridOrder.Refresh();
                updateGridOrder.Update();
                return;
            }

            if (order.StatusID == OrderStatus.Shipped)
            {
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), string.Format("alert('Products have been shipped to customer!');"), true);
                gridOrder.Refresh();
                updateGridOrder.Update();
                return;
            }

            order.StatusID = status;
            order.s_ShipDate = "";
            order.Save();
            gridOrder.Refresh();
            updateGridOrder.Update();
        }

        protected void btnReject_OnClick(object sender, EventArgs e)
        {
            if (hidOrderID.Value != "")
            {
                int orderID = int.Parse(hidOrderID.Value);
                UpdateStatus(orderID, OrderStatus.Rejected);
            }
        }

        public string GetDateLink()
        {
            return "EditPages/SelectDate.aspx";
        }

        protected void btnCreateInvoice_OnClick(object sender, EventArgs e)
        {
            gridOrder.Refresh();
            updateGridOrder.Update();
        }

        protected void btnShip_OnClick(object sender, EventArgs e)
        {
            if (hidOrderID.Value != "" && hidShipDate.Value != "")
            {
                int orderID = int.Parse(hidOrderID.Value);
                POSSystem.BLL.CustomerOrders order = new POSSystem.BLL.CustomerOrders();
                order.LoadByPrimaryKey(orderID);

                if (order.StatusID == OrderStatus.Shipped)
                {
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), string.Format("alert('You have already shipped them to customer!');"), true);
                    gridOrder.Refresh();
                    updateGridOrder.Update();
                    return;
                }

                if (order.StatusID != OrderStatus.InvoiceCreated)
                {
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), string.Format("alert('You have to create invoice for this order before ship it to customer!');"), true);
                    gridOrder.Refresh();
                    updateGridOrder.Update();
                    return;
                }

                order.StatusID = OrderStatus.Shipped;
                order.ShipDate = DateTime.Parse(hidShipDate.Value);
                order.Save();
                gridOrder.Refresh();
                updateGridOrder.Update();
            }
        }

        public string GetSalePageLink()
        {
            return "EditPages/SalePopup.aspx?";
        }
    }
}